package com.longqinuo.mycarservice.fragments;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.entity.KeepServer;
import com.longqinuo.mycarservice.manager.IManager;
import com.longqinuo.mycarservice.manager.MangerImpl;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONException;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MealInfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MealInfoFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private int mId;
    private KeepServer k = new KeepServer();  //套餐对象 用于存入数据库
    private IManager iManager;   //数据库代理管理器
    private boolean isCollect;   //是否收藏过
    private static final int REQUESTCODE = 1;  //打电话请求码
    private String mComName;  //套餐公司名
    private String mPhoneNum;   //套餐公司电话

    private OnFragmentInteractionListener mListener;
    private ImageView iv_back_meal_info;
    private LinearLayout ll_collect_meal;
    private LinearLayout ll_order_server;
    private LinearLayout ll_play_phone;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    private NetworkImageView mBigImage;
    private TextView mTitle;
    private TextView mName;
    private TextView mCurrentPrice;
    private TextView mOldPrice;
    private TextView mOrderCount;
    private LinearLayout ll_car_type_meal;
    private TextView mServerPro;
    private TextView mServerTime;
    private TextView mCompanyName;
    private TextView mCompanyAddress;
    private TextView mCompanyDesc;
    private ImageView mCollectStar; //收藏星星
    private TextView mCollectText;  //收藏文字

    public MealInfoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MealInfoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MealInfoFragment newInstance(String param1, String param2) {
        MealInfoFragment fragment = new MealInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mId = Integer.valueOf(mParam1);
            k.setId(mId); //为对象设置ID
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }
    private void init() {  //初始化操作
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);

        manager = getActivity().getSupportFragmentManager();
        iManager = new MangerImpl(getActivity(),new KeepServer());  //实例化数据库代理管理器
        isCollect = iManager.isExists(mId);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_meal_info, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        iv_back_meal_info = (ImageView) view.findViewById(R.id.iv_back_meal_info);
        iv_back_meal_info.setOnClickListener(this);
        ll_collect_meal = (LinearLayout) view.findViewById(R.id.ll_collect_meal);
        ll_collect_meal.setOnClickListener(this);
        ll_order_server = (LinearLayout) view.findViewById(R.id.ll_order_server);
        ll_order_server.setOnClickListener(this);
        ll_play_phone = (LinearLayout) view.findViewById(R.id.ll_play_phone);
        ll_play_phone.setOnClickListener(this);

        mBigImage = (NetworkImageView) view.findViewById(R.id.niv_image_meal_info);
        mTitle = (TextView) view.findViewById(R.id.tv_meal_title_top);
        mName = (TextView) view.findViewById(R.id.tv_meal_name_info);
        mCurrentPrice = (TextView) view.findViewById(R.id.tv_current_price_meal);
        mOldPrice = (TextView) view.findViewById(R.id.tv_old_price_meal);
        mOrderCount = (TextView) view.findViewById(R.id.tv_order_count_meal);
        ll_car_type_meal = (LinearLayout) view.findViewById(R.id.ll_car_type_meal);
        ll_car_type_meal.setOnClickListener(this);
        mServerPro = (TextView) view.findViewById(R.id.tv_server_pro_meal);
        mServerTime = (TextView) view.findViewById(R.id.tv_server_time_meal);
        mCompanyName = (TextView) view.findViewById(R.id.tv_company_name_meal);
        mCompanyAddress = (TextView) view.findViewById(R.id.tv_company_address_meal);
        mCompanyDesc = (TextView) view.findViewById(R.id.tv_company_desc_meal);
        mCollectStar = (ImageView) view.findViewById(R.id.iv_collect_star_server);
        mCollectText = (TextView) view.findViewById(R.id.tv_collect_text_server);
        initData();
    }

    private void initData() {
        if (isCollect) {
            mCollectText.setText("已收藏");
        } else {
            mCollectText.setText("收藏");
        }
        mCollectStar.setSelected(isCollect);
        mCollectText.setSelected(isCollect);

        requestData();  //请求 套餐数据
    }
    private void requestData() {  //请求车辆详细数据
        JsonObjectRequest request = new JsonObjectRequest(PathUtils.SERVER_INFO+"?id="+mId, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    int code = jsonObject.getInt("code");
                    if (code==0) {
                        JSONObject o = jsonObject.getJSONObject("data");
                        String title = o.getString("name");
                        mTitle.setText(title);
                        mName.setText(title);
                        k.setName(title); //为对象设置Title

                        double price = o.getDouble("price");
                        mCurrentPrice.setText("￥"+price);
                        k.setPrice(price); //为对象设置Price

                        double oldPrice = o.getDouble("originaPrice");
                        mOldPrice.setText("￥"+oldPrice);
                        k.setOriginaPrice(oldPrice); //为对象设置oldPrice

                        int count = o.getInt("pcount");
                        mOrderCount.setText("已预约"+count);
                        k.setCount(count); //为对象设置count

                        String serverContent = o.getString("content");
                         Log.d(">>>>", "服务内容"+serverContent);
                        String contents[] = serverContent.split(",");
                        mServerPro.setText(contents[0]);
                        if (contents.length>0) {
                            mServerTime.setText(contents[1]);
                        }

                        String company = o.getString("company");
                        mComName = company;
                        mCompanyName.setText(company);

                        String place = o.getString("com_location");
                        mCompanyAddress.setText(place);
                        k.setCom_location(place);

                        String desc = o.getString("com_detail");
                        mCompanyDesc.setText(desc);

                        mPhoneNum = o.getString("phone");
                        Log.d(">>>>", "电话"+mPhoneNum);

                        String image = o.getString("image");

                        mBigImage.setImageUrl(PathUtils.SERVER_PHONE+image,imageLoader);
                        k.setImage(image);  //为对象设置Image




                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.iv_back_meal_info:   //返回
                manager.popBackStack();
                break;
            case R.id.ll_collect_meal:   //收藏套餐 或取消
                if (isCollect) {
                    int delete = iManager.delete(k);
                    if (delete!=0) {
                        mCollectText.setText("收藏");
                        Toast.makeText(getActivity(), "取消收藏", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    long add = iManager.add(k);
                    if (add!=0) {
                        mCollectText.setText("已收藏");
                        Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                }
                isCollect = !isCollect;
                mCollectStar.setSelected(isCollect);
                mCollectText.setSelected(isCollect);
                break;
            case R.id.ll_order_server:  //预约看车
                mTransaction.replace(R.id.ll_main_layout, new OrderServerFragment(), "OrderServer");
                mTransaction.addToBackStack("OrderServer");
                mTransaction.commit();
                break;
            case R.id.ll_play_phone:      //拨打电话
                //检查权限
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {

                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                            Manifest.permission.CALL_PHONE)) {

                        new AlertDialog.Builder(getActivity())
                                .setTitle("请求授权")
                                .setMessage("【汽车服务】即将拨打电话，需要您的授权")
                                .setIcon(R.mipmap.ic_launcher)
                                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create()
                                .show();
                    } else {

                        //申请权限
                        ActivityCompat.requestPermissions(getActivity(),
                                new String[]{Manifest.permission.CALL_PHONE},
                                REQUESTCODE);
                    }

                } else {
                    //已经拥有权限进行拨打
                    doCall(mComName);
                }
                break;
            case R.id.ll_car_type_meal:     //查看车辆类型
                break;
        }

    }
    public void doCall(String name) {  //提示是否拨打某公司的电话
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示")
                .setIcon(R.mipmap.ic_launcher)
                .setMessage("是否拨打"+name+"的电话");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                builder.create().dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                doCallPhone();
                builder.create().dismiss();
            }
        });
        builder.create().show();
    }
    public void doCallPhone() {   // 获得权限执行拨打 动作

        Intent intent = new Intent();
        intent.setData(Uri.parse("tel:"+mPhoneNum));
         Log.d(">>>>", "电话号码"+mPhoneNum);
        intent.setAction(Intent.ACTION_CALL);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {  //请求权限回调方法
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUESTCODE:
                if (permissions.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED) {
                    doCallPhone();
                }

        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
